   package com.handong.handdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.handong.handdemo.activity.GetMesActivity;
import com.handong.handdemo.adapter.RingListAdapter;
import com.handong.handdemo.entitiss.FootRingDemo;
import com.handong.handdemo.entitiss.FootRingNewEntity;
import com.handong.handdemo.entitiss.FootRingStatus;
import com.handong.handdemo.entitiss.RingResponse;
import com.handong.handdemo.ui.view.RadarScanView;
import com.handong.handdemo.util.ByteUtils;
import com.handong.handdemo.util.CheckUtil;
import com.handong.handdemo.util.EventBusUtil;
import com.handong.handdemo.util.FootRingNewUtil;
import com.handong.handdemo.util.SPUtil;
import com.handong.handdemo.voice.VoiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;


public class MainActivity extends AppCompatActivity {
    protected static final String TAG ="qwttyuyoiop";
    private InputStream mReadStream;
    private SerialPort mSerialPort;
    private OutputStream mWriteStream;

    private Button loginOut;
    private Button getMeS;
    private RecyclerView mSetRingRV;
    private RadarScanView mRadarScan;
    private RingListAdapter mAdapter;
    private FootRingNewEntity entity;
    private List<FootRingNewEntity> mRingList = new ArrayList<>();
    private int sendTime = 0;

    private VoiceImpl mVoiceImpl;
    private TextToSpeech mTextToSpeech;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.CHANGE_NETWORK_STATE",
            "android.permission.READ_PHONE_STATE",
            "android.permission.CONNECTIVITY_INTERNAL"};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "byte:"+"onCreate");
        setContentView(R.layout.activity_main);
        initView();

        initDatas();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    doWork();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void initView() {
        Log.d(TAG, "byte:"+"initView");
        entity = new FootRingNewEntity();
        mSerialPort = new SerialPort();
        mSetRingRV = findViewById(R.id.searchRingRV);
        mRadarScan = findViewById(R.id.searchRingRS);
        loginOut=findViewById(R.id.sendOrder);
        getMeS=findViewById(R.id.getMesActivity);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mSetRingRV.setLayoutManager(layoutManager);
        mAdapter = new RingListAdapter(R.layout.adapter_ring_list_item, mRingList);
        //启用动画
        mAdapter.setAnimationEnable(true);
        //设置动画方式
        mAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight);
        mSetRingRV.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            connetFootRing();
        });
    }

    private void connetFootRing() {

    }

    private void initDatas() {
        mVoiceImpl = VoiceImpl.getInstance(MainActivity.this);
        try {
            //检测是否有权限
            int permission = ActivityCompat.checkSelfPermission(this,
                    "android.permission.READ_PHONE_STATE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "byte:"+"initDatas");
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            entity.setWork(true);
            loginOut.setVisibility(View.VISIBLE);
            loginOut.setText("点击停止");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true){
                            Thread.sleep(2000);
                            connectDevices();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        });
        loginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                entity.setActionOrder(RingResponse.LOGOUT_ORDER);
//                entity.setStopMissionReceive(false);
//                entity.setStopMissionNoDataCount(0);
                entity.setLoginOutAlarm(true);
                loginOut.setText("已停止");
                getMeS.setVisibility(View.VISIBLE);

            }
        });
        getMeS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, GetMesActivity.class));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "byte:"+"onResume");
    }

    private void doWork() {

        mSerialPort.rfid_poweron();
        try {
            mSerialPort.openSerial(13, 115200);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, e.toString());
        }
        if ((this.mReadStream == null) || (this.mWriteStream == null)) {
            Log.d(TAG, "byte:"+null);

            this.mReadStream = this.mSerialPort.getInputStream();
            this.mWriteStream = this.mSerialPort.getOutputStream();
        }
        try {
            Log.d(TAG, "byte:"+"ssss:"+mReadStream.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                if (mReadStream.available() > 0) {
                    byte[] buff = new byte[mReadStream.available()];//获取全部数据
                    if ((mReadStream.read(buff)) != 0 && buff[0] == 0x68 && buff.length > 6) {
                        Log.d(TAG,"Hello 收："+subStringToComma(ByteUtils.bytesToHexString(buff),2));
                        Log.d(TAG,"收到数据2："+Arrays.toString(buff).split("]")[0].split("\\[")[1]);
                        //刷新列表适配器
                        refreshFootRing(buff);
//                        entity.setRingID("1234");
//                        entity.setSetRingDistance(5);
//                        mRingList.add(entity);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRadarScan.setVisibility(View.GONE);
                                mSetRingRV.setVisibility(View.VISIBLE);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
//                        break;
                    } else {
                        continue;
                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String ringId = "";
    private long ReceiveTime = 0;
    public boolean isStopRecycle = false;
    public boolean isWorking = false;

    public static String byte2String(byte b) {

        return String.format("%02x ", b);
    }

    private void refreshFootRing(byte[] buff) {
        mRingList.clear();
//        if (!ringId.equals("")&&entity.getCurrentIndex()==buff[2])
//        {
//            return;
//        }
        if (!ringId.equals("")) {
            entity.setCurrentIndex(buff[2]);
        }
        ReceiveTime++;
        if (ReceiveTime >= 100000L) {
            ReceiveTime = 0;
        }

        //LogToFileUtils.write("接收次数: "+ReceiveTime);
        //设置脚环序号
        String id = Tools.byteLinkByteToHexString(buff, 3, 2);
        entity.setRingID(id);
        entity.setReceiveData(true);

        //设置手持机id，若为0则没绑定
        String imei_crc = Tools.byteLinkByteToHexString(buff, 5, 2);
        entity.setIMEI_CCR(imei_crc);
        int index = 7;//从第7位开始取数据。
        //脚环距离
        byte tempDistance = buff[index++];//取第7位
        byte tempDistanceFloat = buff[index++];
        int distance = Tools.twoByteToInt(tempDistance, tempDistanceFloat);
        if (distance >= 4000) {//超过40米时不用更新
            if (entity != null) {
                entity.setActualRingDistance(39.9f);
            }
            return;
        }


        if (!ringId.equals("") && entity.getStatus() == FootRingStatus.ESCAPE && entity.getEscapeFirst()) {
            entity.setEscapeFirst(false);
            return;
        }
        if ((tempDistance == 0xC3 && tempDistanceFloat == 0x50) || (!ringId.equals("") && tempDistance == 0x00 && tempDistanceFloat == 0x00)) {
            return;
        }
        float distanceFloat = CheckUtil.floatRoundToInt(distance);
        if (distanceFloat < 0.00F && isStopRecycle) {
            return;
        }
        int receiveCount = entity.getReceiveCount() + 1;
        entity.setReceiveCount(receiveCount);
        float totalDistanceFloat = entity.getTotalRingDistance() + distanceFloat;
        entity.setTotalRingDistance(totalDistanceFloat);
        float averageDistanceFloat = (float) (Math.round(totalDistanceFloat / receiveCount * 10)) / 10;//求平均值并保留一位小数

        Log.e(TAG, "距离测试  接受: " + distanceFloat + ",总数：" + totalDistanceFloat + ",次数:" + receiveCount + ",平均数：" + averageDistanceFloat);
        Log.e(TAG, "距离测试 接受" + tempDistance +"     "+ tempDistanceFloat+"distance:"+distance);
        if (entity.getReceiveCount() != 0) {
            entity.setActualRingDistance(distanceFloat);
        } else {
            entity.setActualRingDistance(0.0F);
        }

        if (!entity.isResponseDistance()) {
            entity.setResponseDistance(true);
        }

        byte checkStatus = buff[index++]; //第9
        entity.setCheckStatus(checkStatus);
        Log.d("我就看看这个value","收："+String.valueOf(checkStatus));
        //锁状态
        int lockType = (checkStatus >> 7) & 0x01;

        if (lockType == FootRingNewEntity.LOCK_OPEN) {
            if (entity.isEmpower()) {
                entity.setLockType(FootRingNewEntity.LOCK_EMPOWER_OPEN);
            } else {
                entity.setLockType(FootRingNewEntity.LOCK_OPEN);
                mVoiceImpl.addSound(R.raw.warning_lock_open);

            }

        } else {

            entity.setLockType(FootRingNewEntity.LOCK_CLOSE);
            mVoiceImpl.addSound(R.raw.warning_ring_gps_lost);
        }
        //防拆状态
        int broken = (checkStatus >> 6) & 0x01;
        if (FootRingNewEntity.LOCK_OPEN == broken) {//拆报警
//            if (mIsPlayWarningVoice && entity.getBrokenType()!=1&&!entity.isEmpower()) {
//                if (mVoiceImpl == null) mVoiceImpl = VoiceImpl.getInstance(mAppContext);
//                mVoiceImpl.addSound(R.raw.warning_ring_broken);
//            }
            entity.setBrokenType(1);
        } else {
            entity.setBrokenType(0);
        }
        //超距状态
        boolean isOverHang = ((checkStatus >> 5) & 0x01) == 0x01;
        entity.setOverHang(isOverHang);
        //脱逃状态
        boolean isEscape = ((checkStatus >> 4) & 0x01) == 0x01;
        entity.setEscape(isEscape);
        //是否震动
        boolean isShake = ((checkStatus >> 3) & 0x01) == 0x01;
        entity.setShake(isShake);
        //是否低电量
        boolean isPowerLow = ((checkStatus >> 2) & 0x01) == 0x01;
        entity.setPowerLow(isPowerLow);
        //是否低电量关机
        boolean isPowerDown = ((checkStatus >> 1) & 0x01) == 0x01;
        entity.setPowerDown(isPowerDown);
        if (isPowerDown) {
            FootRingNewUtil.unbind(entity);
                    entity.setNormalWork(false);
            sendDealOrder(entity, RingResponse.LOGOUT_ORDER, true);
            return;
        }


        byte modelStatus = buff[index++];   //di 10
        //是否注销
        boolean isLoginOut = (modelStatus >> 7 & 0x01) == 0x01;
        if (isLoginOut && !isStopRecycle) {

            FootRingNewUtil.unbind(entity);
            entity.setNormalWork(false);
            sendDealOrder(entity, RingResponse.LOGOUT_ORDER, true);
            if (!isWorking) {
                mRingList.remove(entity);
//                mSerialPortUtil.setRingList(mRingList);
            }

            //mRingList.remove(entity);

            return;
        }
        entity.setLoginOut(isLoginOut);
        //是否返回状态
        boolean isResult = (modelStatus >> 6 & 0x01) == 0x01;
        entity.setResult(isResult);
        //是否正在报警
        boolean isSouding = (modelStatus >> 5 & 0x01) == 0x01;
        entity.setSouding(isSouding);
        boolean isAudioError = (modelStatus >> 4 & 0x01) == 0x01;
        entity.setAudioError(isAudioError);
        //UWB是否初始化成功
        boolean isUwebError = (modelStatus >> 3 & 0x01) == 0x01;
        entity.setUwbError(isUwebError);
        //4G模块初始化成功
        boolean is4gError = (modelStatus >> 2 & 0x01) == 0x01;
        entity.setIs4gError(is4gError);
        //Sim是否正常
        boolean isSimError = (modelStatus >> 1 & 0x01) == 0x01;
        entity.setSimError(isSimError);
        //发送imei错误提示
        if (isSimError && !entity.isSimError()) {
            EventBusUtil.post(new RingResponse(id, RingResponse.SIM_ERROR, false));
        }
        //WiFi模块是否正常
        boolean isWifiError = (modelStatus & 0x01) == 0x01;
        entity.setWifiError(isWifiError);

        //任务应答
        byte taskResp = buff[index++];  //11
        entity.setTaskResp(taskResp);

        //电量
        int power = (int) (buff[index++] & 0xff);  //12
//        if (entity.getRingPower()==0)
//        {
        //power=testpower--;
        int truePower=getpower(power);
        entity.setRingPower(truePower);

        String version=String.valueOf(buff[index++] & 0xff);
        entity.setVersion(version);
//        }
//        else if((entity.getRingPower()-power)>=10||(entity.getRingPower()-power)<=-10){
//            entity.setRingPower(power);
//        }
        //软件版本
//        int version=buff[index++];
//        String versionStr=String.valueOf(version);
//        String versionHigh=versionStr.substring(0,1);
//        String versionLow=versionStr.substring(1,2);
//        entity.setVersion("V"+versionHigh+"."+versionLow);
        String ss=String.format("收到数据：脚环id:%s,手持机id:%s,距离%s,锁状态:%d ,电量:%d  ",id,imei_crc,averageDistanceFloat,lockType,truePower);
        Log.d(TAG,ss);
        //设置状态
        if (imei_crc.equals("0000")) {
            entity.setNormalWork(false);
        } else {
            entity.setNormalWork(true);
        }
        FootRingNewUtil.setMyBingding(entity, imei_crc);
        if (entity.isHandAlarm()) {
            entity.setHandAlarm(false);
        }
//        Gson gson=new Gson();
        //LogToFileUtils.write("Receive Data:" + Tools.byteToHexString(buff));
        //LogToFileUtils.write(gson.toJson(entity));
//        if (!mSerialPortUtil.currentCode.equals("")&&mSerialPortUtil.currentCode.equals(entity.getRingID()))
//        {
//            mSerialPortUtil.mBindedRingList.remove(entity.getRingID());
//            mSerialPortUtil.sendIMEI();
//        }
        //设置当前的超距位
        if (!entity.isOverSetDistance() && entity.getActualRingDistance() >= entity.getSetRingDistance()) {
            entity.setOverSetDistance(true);
        }
        if (entity.isOverSetDistance() && entity.getActualRingDistance() < entity.getSetRingDistance()) {
            entity.setOverSetDistance(false);
        }

//        mSerialPortUtil.setRingList(mRingList);

        //处理命令
        if (entity != null && entity.getActionOrder() != RingResponse.NO_ACTION_ORDER) {
            switch (entity.getActionOrder()) {


                case RingResponse.ACTIVATE_ORDER://脚环激活
                    if (imei_crc.equals(SPUtil.getStringValue(SPUtil.IMEI_CRC))) {
                        FootRingNewUtil.unbind(entity);
                        sendDealOrder(entity, RingResponse.INIT_2GNET_SUCCESS, true);
                        //mSerialPortUtil.order++;
                    }
                    break;
                case RingResponse.UPDATE_DISTANCE_ORDER://设置距离
                    sendDealOrder(entity, RingResponse.UPDATE_DISTANCE_ORDER, true);
                    break;

                case RingResponse.CLOSE_ALARM_RESPONSE://关闭警报
                    if (RingResponse.CLOSE_ALARM_RESPONSE == entity.getActionOrder()) {
                        sendDealOrder(entity, RingResponse.CLOSE_ALARM_RESPONSE, true);
//                        mSerialPortUtil.closeAlarmOrder2Server(entity.getRingID());
//                        mUploadCount = 5;
                    } else {
                        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);
//                        mSerialPortUtil.resetOrder2Server(entity.getRingID());
//                        mUploadCount = 5;
                    }
                    break;

            }
        }

        entity.resetTime();//重置时间
        //发送命令
        //onSendDataListener.onSend(entity);
        entity.setCreateTime(System.currentTimeMillis() / 1000);
        mRingList.add(entity);
    }

    private int getpower(int battery) {
        int temp = 0;
        if (battery >= 175) {//4.15
            temp = 100;
        } else if (battery >= 161) {//90 9
            temp = 90;
        } else if (battery >= 148) {//80 9
            temp = 80;
        } else if (battery >= 133) {//70 10
            temp = 70;
        } else if (battery >= 118) {//60 10
            temp = 60;
        } else if (battery >= 102) {//50 11
            temp = 50;
        }else if (battery >= 89) {//40 3.6
            temp = 40;
        }else if (battery >= 74) {//30 12
            temp = 30;
        }else if (battery >= 59) {//20 13
            temp = 20;
        }else if (battery > 52) {//10 3.34
            temp = 10;
        }else {//5
            temp = 0;
        }
        return temp;

    }

    /**
     * 发送处理脚环结果
     */
    private void sendDealOrder(FootRingNewEntity entity, byte order, boolean isSuccess) {
        if (entity == null) {
            return;
        }
        entity.resetActionCount();
        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);//重置为已处理
        EventBusUtil.post(new RingResponse(entity.getRingID(), order, isSuccess));
    }

    private void connectDevices() {
        FootRingNewEntity entity = mRingList.get(0);
        Log.e(TAG, "list长度：:" + mRingList.size() + "sid:" + entity.getRingID());
        entity.setActionOrder(RingResponse.ACTIVATE_ORDER);
        //entity.setTaskTime(order);
        byte j = 0;
        entity.setUwbCycle(j);
        j++;
        entity.setIsActive(32);

        if (this.mWriteStream == null) {
            Log.e(TAG, "s" +
                    "流是空的：:" + entity.getUwbCycle());
            return;
        }
        byte[] sendData = getSendStrByFootRingEntity(entity);
        sendTime++;
        Log.e(TAG, "发送次数" + sendTime + "Send Data:" + Arrays.toString(sendData));
        try {
            this.mWriteStream.write(sendData);
            entity.setTaskTime((byte) 0);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "循环发送命令" + Tools.byteToHexString(sendData) + "。");
        }
    }

    public byte[] getSendStrByFootRingEntity(FootRingNewEntity entity) {
        //头
        StringBuilder result = new StringBuilder("6864");
        //序号
        //result.append(getSequence());
        //脚环id

//            if (entity.getRingID() == null) {
//                result.append("0000");
//            } else {
        result.append(entity.getRingID());
//            }
        Log.e(TAG, "imei:：:" + Tools.getIMEI(this) + "          :" + (Tools.getIMEI_CCR(Tools.getIMEI(this)).toUpperCase()));
        //手持机id
        if (Tools.getIMEI(this) != "") {
            result.append((Tools.getIMEI_CCR(Tools.getIMEI(this)).toUpperCase()));
        } else {
            result.append("BF41");
        }

        Log.e(TAG, "result:：:" + result);
        //设定距离，当前小数部分为0
        result.append(Tools.intToHexString(entity.getSetRingDistance()));
        //报警相关
        int voice = 0;
        if (entity.isLockAlarm()) {
            voice += 128;
        }
        if (entity.isBreakAlarm()) {
            voice += 64;
        }
        if (entity.isOverHangAlarm()) {
            voice += 32;
        }
        if (entity.isEscapeAlarm()) {
            voice += 16;
        }
        if (entity.isShakeAlarm()) {
            voice += 8;
        }
        if (entity.isHandAlarm()) {
            voice += 4;
        }
        if (entity.isStopAlarm()) {
            voice += 2;
        }
        if (entity.isLoginOutAlarm()) {
            voice += 1;
        }

        result.append(Tools.intToHexString(voice));
        Log.e(TAG, "result void" + result);
        byte task = 0x00;


        if (entity.isWork()) {
            task += 16;
        }
        if (entity.isPhoneSend()) {
            task += 8;
        }
        //task
        result.append(Tools.byteToHexString(task));
        Log.d("我就看看这个value","发："+entity.isWork()+"    :"+entity.isPhoneSend());
        Log.d("我就看看这个value","发："+Tools.byteToHexString(task));
        Log.e(TAG, "tesk:" + result);
        //task_time
        result.append(Tools.byteToHexString(entity.getTaskTime()));
        Log.e(TAG, "result:time:" + result);
        //uwb_cycle
        result.append(Tools.byteToHexString(entity.getUwbCycle()));
        //result.append("000000");
        //是否激活
        Log.e(TAG, "result:cycle:" + result);

        result.append(Tools.intToHexString((entity.getIsActive())));
        Log.e(TAG, "result:getIsActive:" + entity.getIsActive()+"zhuan:"+Tools.intToHexString((entity.getIsActive())));
        Log.e(TAG, "result:jihuo:" + result);
        //checkstatus
//        result.append(Tools.byteToHexString(entity.getCheckStatus()));
        result.append("00");
        Log.d("我就看看这个value","发："+String.valueOf(entity.getCheckStatus()));
        Log.d("我就看看这个value","发："+ Tools.byteToHexString(entity.getCheckStatus()));
        //实际距离
        float actualRingDistance = entity.getActualRingDistance();
        int actualRingDistanceInt = Math.round(actualRingDistance * 100);
        String hightDistance = Tools.intToHexString(actualRingDistanceInt / 100);
        String lowDistance = Tools.intToHexString(actualRingDistanceInt % 100);
        result.append(hightDistance + lowDistance);
        Log.e(TAG, "距离测试 发送" + hightDistance +"     "+ lowDistance);
        if (entity.getRingPower() < 0) {
            result.append("00");
        } else {
            result.append(Tools.intToHexString(entity.getRingPower()));
        }
        //result.append("00000000");

        //ip+端口
        String ip = "111.230.245.184";
        int port = 8205;
        String[] ipArr = ip.split("\\.");
        for (String ipString :
                ipArr) {
            result.append(Tools.intToHexString(Integer.parseInt(ipString)));
        }
        result.append(Tools.intToHexString(port, 4));
        //是否检查模块
        //result.append(Tools.intToHexString(entity.getIsCheck()));
        Log.e(TAG, "result:ip:" + result);
        //是否同步
        //result.append(Tools.intToHexString(entity.getIsSync()));
        Log.d(TAG, "Hello 发:" +subStringToComma(result.toString(),2) );
        byte[] resultStr = CheckUtil.checkSum8Caculation(result.toString());
        //Tools.str2HexStr("\r\n");
        Log.e(TAG, "Send Data:" + result);
        //result+=entity.getActualRingDistance();
        return resultStr;
    }

    public static String subStringToComma(String str, Integer regex) {
        char[] chars = str.toCharArray();
        String temp = "";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i <= chars.length - 1; i++) {
            temp += chars[i];
            if (i == chars.length - 1) {
                result.append(temp);
                break;
            }
            if (temp.length() >= regex) {
                temp += ",";
                result.append(temp);
                temp = "";
            }
        }
        return result.toString();

    }
}